package com.lujianfei.powersearch.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.widget.Toast
import com.lujianfei.powersearch.logger.LoggerFactory

object AppJumpUtils {

    private val log = LoggerFactory.getLogger()

    private val TAG = "AppJumpUtils"

    fun startWebLink(context: Context?, url:String) {
        runCatching {
            val intent = Intent()
            intent.action = Intent.ACTION_VIEW
            intent.data =  Uri.parse(url)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context?.startActivity(intent)
        }
    }

    fun startPhone(context: Context?, url:String) {
        runCatching {
            val intent = Intent()
            intent.action = Intent.ACTION_DIAL
            intent.data =  Uri.parse("tel: $url")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context?.startActivity(intent)
        }
    }

    fun startMap(context: Context?, keywords: String?, sourceApplication:String = "powersearch") {
        val uriString = StringBuilder()
        uriString.append("androidamap://poi?sourceApplication=${sourceApplication}")
        if (keywords != null) {
            uriString.append("&keywords=${keywords}")
        }
        startUri(context, uriString.toString())
    }

    private fun startUri(context: Context?, uriString: String) {
        log.d(TAG, "startUri: $uriString")
        try {
            val intent = Intent()
            intent.setAction(Intent.ACTION_VIEW)
            intent.addCategory(Intent.CATEGORY_DEFAULT)
            val uri = Uri.parse(uriString)
            intent.setData(uri)
            //启动该页面即可
            context?.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
        } catch (e: Exception) {
            log.e(TAG, "${e}", e)
            Toast.makeText(context, "${e}", Toast.LENGTH_SHORT).show()
            return
        }
    }

}